var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();


// 设置允许跨域访问，必须设置在接口请求前
// app.all("*",function(req,res,next){
//   res.header("Access-Control-Allow-Origin","*");
//   res.header("Access-Control-Allow-Headers","content-type");
//   res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
//   req.method.toLowerCase() == 'options' ? res.send(200) : next();
// });

// multer用于处理 multipart/form-data 类型的表单数据,需要引入multer库
const multer = require('multer');
// 自定义保存文件名
let storage = multer.diskStorage({
	destination: 'public/uploaded/',
	filename: function(req,file,cd){
		//获取后缀名
		const extname = path.extname(file.originalname)
		cd(null , file.fieldname + Date.now() + extname)
	}//是自定义的文件名。
})
let upload = multer({storage:storage}).single('file');//file为上传时的name值。

// 上传图片接口
app.post('/uploader', upload, function (req ,res, next){
	const url = '/' + req.file.path;
	res.json({
		code: 0, 
		msg: '上传成功！', 
		data: {
			src: url,
			title: req.file.originalname
		}
	})
})

// 渲染前端页面
app.get('/layedit', (req, res, next) => {
	res.render('index.html');
});

// express生成项目自带的模版引擎jade
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// html渲染模版引擎，需要引入express-art-template和art-template两个库
app.engine('html',require('express-art-template'));

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

// 设置静态文件目录
app.use('/public',express.static(path.join(__dirname, 'public')));
// 这是用express生成项目自带的，无效
// app.use(express.static(path.join(__dirname, 'public')));



app.use('/', indexRouter);
app.use('/users', usersRouter);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
